package com.alogic.es.xscript;

import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.lang3.StringUtils;

/**
 * 文档的命令操作
 *
 * @since 1.6.13.9 [20200824 duanyy]
 */
public class EsCommandDoc extends EsCommand{
    protected String $id = "";

    public EsCommandDoc(String tag, Logiclet p) {
        super(tag, p);
    }
    public EsCommandDoc(String tag, Logiclet p, String src) {
        super(tag, p,src);
    }

    @Override
    public void configure(Properties p) {
        super.configure(p);
        $id = PropertiesConstants.getRaw(p,"id","");
    }

    @Override
    protected void onExecute(XsObject root, XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
        if (script == null){
            log(String.format("[%s]Script is null ,ignored..",this.getXmlTag()),"warnning");
            return ;
        }
        String docId = PropertiesConstants.transform(ctx,$id,"");
        if (StringUtils.isNotEmpty(docId)){
            try {
                if (callbackRequest != null) {
                    ctx.setObject(callbackRequestId, callbackRequest);
                }
                if (callbackResponse != null) {
                    ctx.setObject(callbackResponseId, callbackResponse);
                }
                ctx.SetValue("$es-doc-id",docId);
                script.execute(root, current, ctx, watcher);
            }finally{
                ctx.removeObject(callbackRequestId);
                ctx.removeObject(callbackResponseId);
            }
        }else{
            log(String.format("[%s]doc id is null ,ignored..",this.getXmlTag()),"warnning");
        }
    }
}
